from app.database.connector import Database
from app.database.dao import BaseDAO
from datetime import datetime

class OperationDAO(BaseDAO):
    def __init__(self, db=None):
        super().__init__('operation_logs', db)
        self.datetime_fields = ['created_at']

    def _format(self, data):
        """格式化日期时间字段"""
        if not data:
            return data
        
        result = data.copy()
        for field in self.datetime_fields:
            if field in result and result[field]:
                if isinstance(result[field], datetime):
                    result[field] = result[field].strftime('%Y-%m-%d %H:%M:%S')
        return result

    def get_operation_list(self, page=1, page_size=10, conditions=None, order_by='created_at', order='desc'):
        """获取操作日志列表"""
        where_clauses = []
        params = []
        
        if conditions:
            for key, value in conditions.items():
                if isinstance(value, str) and key.endswith(' LIKE'):
                    field_name = key[:-5]
                    where_clauses.append(f"{field_name} LIKE %s")
                    params.append(f"%{value}%")
                else:
                    where_clauses.append(f"{key} = %s")
                    params.append(value)
        
        # 构建查询语句
        query = f"SELECT * FROM {self.table_name}"
        if where_clauses:
            query += " WHERE " + " AND ".join(where_clauses)
        
        # 添加排序
        query += f" ORDER BY {order_by} {order}"
        
        # 添加分页
        query += " LIMIT %s OFFSET %s"
        params.extend([page_size, (page - 1) * page_size])
        
        results = self.db.execute_query(query, tuple(params))
        return [self._format(item) for item in results]

    def get_total_count(self, conditions=None):
        """获取符合条件的记录总数"""
        where_clauses = []
        params = []
        
        if conditions:
            for key, value in conditions.items():
                if isinstance(value, str) and key.endswith(' LIKE'):
                    field_name = key[:-5]
                    where_clauses.append(f"{field_name} LIKE %s")
                    params.append(f"%{value}%")
                else:
                    where_clauses.append(f"{key} = %s")
                    params.append(value)
        
        query = f"SELECT COUNT(*) as total FROM {self.table_name}"
        if where_clauses:
            query += " WHERE " + " AND ".join(where_clauses)
            
        result = self.db.execute_query(query, tuple(params))
        return result[0]['total'] if result else 0